import requests
from common.config import cfg
async def login_wechat_backend(code):
    # 请求微信服务器换取openid和session_key
    APP_ID = cfg['wechat']['app_id']
    APP_SECRET = cfg['wechat']['app_secret']
    url = f'https://api.weixin.qq.com/sns/jscode2session?appid={APP_ID}&secret={APP_SECRET}&js_code={code}&grant_type=authorization_code'
    response = requests.get(url)
    if response.status_code != 200:
        return False, '请求微信服务器失败'
    res_data = response.json()
    if 'errcode' in res_data:
        return False, res_data.get('errmsg', '未知错误')
    openid = res_data.get('openid')
    session_key = res_data.get('session_key')
    if not openid or not session_key:
        return False, "获取openid或session_key失败"
    return True, {'openid':openid, 'session_key':session_key}

# async def get_access_token():
#     APP_ID = cfg['wechat']['app_id']
#     APP_SECRET = cfg['wechat']['app_secret']
#     url = f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APP_ID}&secret={APP_SECRET}'
#     response = requests.get(url)
#     res_data = response.json()
#     if 'errcode' in res_data:
#         return False, res_data['errmsg']
#     access_token = res_data['access_token']
#     return True, access_token

# async def get_phone_number(code):
    # 获取access_token
    ret, access_token = await get_access_token()
    if not ret:
        return False, access_token
    print(access_token)
    # 使用微信提供的API获取手机号
    url = f"https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={access_token}"
    payload = {
        "code": code
    }
    response = requests.post(url, json=payload)
    res_data = response.json()
    print(res_data)
    if 'errcode' in res_data and res_data['errcode'] != 0:
        return False, res_data.get('errmsg', '未知错误')
    phone_info = res_data.get('phone_info', {})
    phone_number = phone_info.get('phoneNumber')
    return True, phone_number